package zsl.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class WordCountList {
	private ArrayList<WordCount> list;
	private HashMap<String, Integer> map;
	
	public WordCountList() {
		list = new ArrayList<>();
		map = new HashMap<>();
	}
	
	public WordCountList(int initLen){
		list = new ArrayList<>(initLen);
		map = new HashMap<>(initLen);
	}
	
	public void add(WordCount wc){
		list.add(wc);
		map.put(wc.word, wc.count);
	}
	
	public void addInDescOrder(WordCount wc){
		int size = list.size();
		for (int i = 0; i < size; i++) {
			if (list.get(i).getCount() <= wc.getCount()) {
				list.add(i, wc);
				map.put(wc.word, wc.count);
				return;
			}
		}
		
		list.add(wc);
		map.put(wc.word, wc.count);
	}
	
	public WordCount get(int index){
		return list.get(index);
	}
	
	public int getCount(String word){
		Integer count = map.get(word);
		return count == null ? 0 : count;
	}
	
	//get count in current list from a wordCount in another list
	public int getCount(WordCount wc){
		return map.get(wc.word);
	}
	
	public int size(){
		return list.size();
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		for (WordCount wordCount : list) {
			sb.append(wordCount.toString()+",");
		}
		return sb.deleteCharAt(sb.length()-1).append("}").toString();
		
//		return list.toString();
	}
	
	public boolean contains(String word) {
		return map.containsKey(word);
	}
	
	public void clear(){
		list.clear();
		map.clear();
	}
	
	public void descOrder(){
		Collections.sort(list);
	}
	
	public WordCountList clone(){
		int size = list.size();
		WordCountList clonedList = new WordCountList(size);
		for (int i = 0; i < size; i++) {
			WordCount wordCount = list.get(i);
			clonedList.add(new WordCount(wordCount.word, wordCount.count));
		}
		return clonedList;
	}
}
